import { computed, onMounted } from 'vue'
import { defineStore } from 'pinia'
import { cloneDeep, keyBy } from 'lodash-es'
import { useLocalStorage } from '@vueuse/core'
import { StorageEnum } from '@/core/enums/shared'
import { serializer } from '@/utils'

export interface Region {
  id: string
  name: string
  name_cn: string
  parent: string
  area_type: number
  baidu_code: string
  sogou_code: string
  qihu_code: string
  sm_code: string
  sm_new_code: string
  is_allowed: number
  children: Region[]
}

// 上海北京等直辖市parent改为zhixiashi
function centralGovernment(r: Region[]) {
  r.filter((d) => ['上海', '北京', '天津', '重庆'].includes(d.name_cn)).forEach((item) => {
    item.parent = 'zhixiashi'
  })

  return r
}

function formatRegion(items: Region[]) {
  const result: Region[] = []

  const itemMap = items.reduce<Record<string, Region>>((p, n) => {
    p[n.id] = {
      ...n,
      children: []
    }
    return p
  }, {})

  items.forEach((d) => {
    const treeItem = itemMap[d.id]
    if (d.parent === '') {
      result.push(treeItem)
    } else {
      if (['上海', '北京', '天津', '重庆'].includes(d.name_cn)) {
        if (itemMap['zhixiashi']) {
          itemMap['zhixiashi'].children?.push(treeItem)
        }
      } else {
        if (!itemMap[d.parent]) {
          itemMap[d.parent]['children'] = []
        }
        itemMap[d.parent].children?.push(treeItem)
      }
    }
  })

  return result
}

export const useRegionStore = defineStore('Region', () => {
  const storeRegion = useLocalStorage<Region[]>(StorageEnum.REGION, null, {
    serializer
  })
  const rawRegion = computed(() => centralGovernment(storeRegion.value || []))
  const region = computed(() => formatRegion(rawRegion.value))
  const mapRegion = computed(() => keyBy(rawRegion.value, 'name'))
  const mapChineseRegion = computed(() => keyBy(rawRegion.value, 'name_cn'))

  async function initRegion() {
    if (!rawRegion.value.length) {
      // @ts-ignore
      const r = await import('/public/static/region.json')
      const data = cloneDeep(r.data)
      data.push({
        id: 'zhixiashi',
        name: 'zhixiashi',
        name_cn: '直辖市',
        parent: 'china',
        area_type: 1,
        baidu_code: '',
        sogou_code: '',
        qihu_code: '',
        sm_code: '直辖市',
        sm_new_code: '',
        is_allowed: 1,
        children: []
      })

      storeRegion.value = data
    }
  }

  function removeRegion() {
    storeRegion.value = null
  }

  onMounted(async () => {
    await initRegion()
  })

  return {
    region,
    rawRegion,
    mapRegion,
    mapChineseRegion,
    removeRegion,
    initRegion
  }
})
